package com.example.springboot.controller;

import com.example.springboot.dao.UserDao;
import com.example.springboot.exception.MyException;
import com.example.springboot.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@Controller
public class UserController {

    @Autowired
    UserDao userDao;

    /**
     * 获取所有用户 , 并跳转到all_user.html
     *
     * @param model
     * @return
     */
    @GetMapping("/emps")
    public String list(Model model) {
        Collection<User> all = userDao.getAll();
        model.addAttribute("emps", all);
        return "all_user";
    }

    /**
     * 跳转到edit_user.html
     *
     * @param model
     * @return
     */
    @GetMapping("/emp")
    public String toAddPage(Model model) {
        return "edit_user";
    }

    /**
     * 添加用户接口,添加之后跳转到all_user.html
     *
     * @param user
     * @return
     */
    @PostMapping("/emp")
    public String addPage(User user) {
        userDao.addUser(user);
        return "redirect:/emps";
    }

    /**
     * 获取id,并跳转到edit_user.html页面
     *
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/emp/{id}")
    public String toEditPage(@PathVariable("id") Integer id, Model model) {
        User user = userDao.getUser(id);
        model.addAttribute("user", user);
        return "edit_user";
    }

    /**
     * 修改用户接口
     *
     * @param user
     * @return
     */
    @PutMapping("/emp")
    public String editUser(User user) {
        int id = userDao.updateUser(user);
        return "redirect:/emps";
    }


    /**
     * 删除接口 , 需要添加配置 :spring.mvc.hiddenmethod.filter.enabled = true
     *
     * @param id
     * @return
     */
    @DeleteMapping("/emp/{id}")
    public String deleteUser(@PathVariable("id") Integer id) {
        int num = userDao.removeUser(id);
        return "redirect:/emps";
    }


    /**
     * 自定义返回错误页面状态码
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/hello")
    public String testException(@RequestParam("id") Integer id) {
        if (id.equals(1)) {
            throw new MyException();
        }
        return "hello";
    }


    /**
     * 跨域请求测试
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/cors/test", method = RequestMethod.POST)
    public String testCors() {
        return "asd";
    }

}
